// import MD5 from './md5.js';
import MD5 from './new_md5.js';
// import VueResource from 'vue-resource';
// import $RS from 'common/routerSwitch.js';
// let $http = new VueResource();
import $ from '../../static/dateScroll/jquery-1.9.1.js';
export default {
  getUrlKey: function (name) {
    console.log(name)
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
  },
  getMD5: function (str) {
    return MD5.getMD5(str);
  },
  getSign: function (obj, timeStamp) {
    console.log(obj);
    let key = '8c89b98624bccfce4616a07242dae977';
    let str = '';
    let objKeys = Object.keys(obj);
    objKeys.sort(function (a, b) {
      let c = a.length > b.length ? b.length : a.length;
      for (let i = 0; i < c; i++) {
        let al = a.charCodeAt(i);
        let bl = b.charCodeAt(i);
        if (al !== bl) {
          // console.log(al - bl)
          return al - bl;
        }
      }
      // console.log("false");
      if (c === a.length) {
        return -1;
      } else {
        return 1;
      }
    });
    // console.log(objKeys);
    for (let i = 0; i < objKeys.length; i++) {
      let key = objKeys[i];
      if (obj[key]) {
        str += ('&' + key + '=' + obj[key]);
      }
      // console.log(str);
    }
    str = str.substring(1) + '&key=' + key + '&timestamp=' + timeStamp;
    console.log(str);
    return this.getMD5(str);
  },
  getNewSign: function (obj, timestamp) {
    console.log('getNewSign');
    let secert = '8c89b98624bccfce4616a07242dae977';
    let preSign = null;
    if (obj) {
      if (obj instanceof Object && !(obj instanceof Array)) {
        preSign = this.obj2str(null, obj);
      } else if (content instanceof Array) {
        preSign = this.arr2str(null, obj);
      }
      preSign = preSign + 'key=' + secert + '&timestamp=' + timestamp;
    }
    console.log(preSign);
    return this.getMD5(preSign);
  },
  obj2str: function (preKey, obj) {
    let preSign = '',
      arrKeys = [];
    for (let key in obj) {
      arrKeys.push(key);
    }
    arrKeys.sort();
    for (let i in arrKeys) {
      let key = arrKeys[i],
        value = obj[key];
      key = (preKey ? preKey + '.' : '') + key;
      if (this.isVal(value)) {
        preSign += key + '=' + value + '&';
      } else if (value instanceof Object && !(value instanceof Array)) {
        preSign += this.obj2str(key, value);
      } else if (value instanceof Array) {
        preSign += this.arr2str(key, value);
      }
    }
    return preSign;
  },
  arr2str: function (preKey, arr) {
    let preSign = '';
    for (let i = 0; i < arr.length; i++) {
      let key = (preKey ? preKey : '') + '[' + i + ']';
      let value = arr[i];
      if (this.isVal(value)) {
        preSign += key + '=' + value + '&';
      } else if (value instanceof Object && !(value instanceof Array)) {
        preSign += this.obj2str(key, value);
      } else if (value instanceof Array) {
        preSign += this.arr2str(key, value);
      }
    }
    return preSign;
  },
  isVal: function (obj) {
    return ((typeof obj == 'string') && obj.constructor == String) ||
      ((typeof obj == 'number') && obj.constructor == Number) ||
      ((typeof obj == 'boolean') && obj.constructor == Boolean);
  },
  // getCookies: function (name) {
  //   let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  //   if (arr = document.cookie.match(reg))
  //     return (arr[2]);
  //   else
  //     return null;
  // },
  // setCookies: function (c_name, value, expiredays) {
  //   let exdate = new Date();
  //   exdate.setDate(exdate.getDate() + expiredays);
  //   document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
  // },
  setSession: function (name, item) {
    let type = typeof item;
    if (type == 'string' || type == 'number') {
      sessionStorage.setItem(name, item);
    }
    if (type == 'object') {
      sessionStorage.setItem(name, JSON.stringify(item));
    }
  },
  getSession: function (name) {
    let str = sessionStorage.getItem(name);
    if (!str) {
      return '';
    }
    return JSON.parse(str);
  },
  removeSession: function (name) {
    if (name)
      sessionStorage.removeItem(name);
  },
  getUserContent: function (content, getNew = false) {
    console.log(content)
    let timestamp = new Date().getTime() + '';
    // for (let key in content) {
    //   if (typeof content[key] != 'number' && !content[key]) {
    //     delete content[key];
    //   }
    //   if (content[key] instanceof Array) {
    //     for (let i = 0; i < content[key].length; i++) {
    //       content[key + '[' + i + ']'] = content[key][i]
    //     }
    //     delete content[key];
    //   }
    // }
    let data = {
      headers: {
        // "devModel": "iPhone",
        appPlatform: 'NativeH5',
        // "devSystem": "iOS",
        // "devImei": "BDC9921442384C6A",
        appFrom: 'westAirH5',
        // "systemVersion": "0",
        // "versionCode": "0",
        // "devToken": "BDC9921442384C6A",
        timestamp: timestamp
      },
      // sign: getNew ? this.getNewSign(content, timestamp): this.getSign(content, timestamp),
      sign: this.getNewSign(content, timestamp),
      content: content
    };
    return data;
  },
  regTest: function (item, type, vue) { // 校验 通过返回该数据，否则返回false
    const REGS = {
      password: {
        // reg: /^[\d\w]{6,14}$/,
        reg: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
        msg: '请输入符合规定的密码'
      },
      phoneNum: {
        reg: /^1\d{10}$/,
        msg: '请输入正确的电话号码'
      },
      id: {
        // reg: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/,
        reg: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
        msg: '请输入正确的身份证号码'
      },
      yzm: {
        reg: /^\d{6}$/,
        msg: '请输入正确的验证码'
      },
      passport: {
        // reg: /^[0-9a-zA-Z]{2,44}$/,
        reg: /^[a-zA-Z0-9]{4,44}$/,
        msg: '请输入正确的证件号'
      },
      cname: {
        // reg: /^[\u4e00-\u9fa5]{1,12}$/,
        reg: /^[\u4e00-\u9fa5a-zA-Z\s]{1,24}$/,
        msg: '请输入合规的中文姓名'
      },
      ename: {
        // reg: /^[\w]{1,24}$/,
        reg: /^[a-zA-Z0-9\s]{1,24}$/,
        msg: '请输入合规的英文姓名'
      },
      anyName: {
        reg: /^([\u4e00-\u9fa5a-zA-Z\s]{1,24})|([a-zA-Z0-9\s]{1,24})$/,
        msg: '请输入合规的姓名'
      },
      email: {
        reg: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
        msg: '请输入合规的邮箱'
      },
      ticketNo:{
        reg:/^847-\d{10}$/,
        msg: '请输入合规的票号'
      },
      EName: {
        // reg: /^\S[A-Za-z\s]{2,}$/,
        reg: /[a-zA-Z0-9\s]{1,24}/,
        msg: '请输入合规的英文姓名'
      }
    };
    let regObj = REGS[type];
    if (!regObj) {
      console.log(type + '类型不存在,at untils.js');
      return false;
    }
    if (!regObj.reg.test(item)) {
      vue.$store.dispatch('showTx', {
        text: regObj.msg
      });
      return false;
    }
    return item;
  },
  formatTime: function (ms) {
    const DAY = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    let now = new Date(ms);
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let date = now.getDate();
    let hour = now.getHours();
    let min = now.getMinutes();
    let week = DAY[now.getDay()];
    month < 10 && (month = '0' + month);
    date < 10 && (date = '0' + date);
    hour < 10 && (hour = '0' + hour);
    min < 10 && (min = '0' + min);
    let str = {
      first: year + '-' + month + '-' + date,
      second: hour + ':' + min,
      third: week,
      four: {
        year,
        month,
        date
      }
    }
    return str;
  },
  getWeek: function (str) {
    str.replace('-', '/')
    let date = new Date(str).getTime();
    // console.log(this.formatTime(date));
    return this.formatTime(date);
  },
  ajax: function (data, action, vue, callbak, errCb) {
    // let options = {
    //   emulateJSON: isoldPort
    // }
    vue.$store.commit('showLoading');
    vue.$http.post(vue.$RS[action], data).then(
      function (res) {
        // 响应成功回调
        vue.$store.commit('closePop');
        res = res.body;
        console.log(res.code);
        if (res.code === 1000) {
          console.log('in');
          // let userInfo = res.content;
          // // console.log(userInfo);
          // vue.$store.commit('setLogin', userInfo);
          // // console.log(this.$store.state.loginData);
          // // 设置sessionStorage
          // vue.$utils.setSession('loginData', userInfo)
          // vue.$router.go('-1');
          if (callbak) {
            callbak(res);
          }
        } else if (res.code === 4110 || res.code === 2066) {
          vue.$store.dispatch('showTx', {
            text: '您需要重新登录'
          });
          vue.$router.push('/login');
        } else {
          console.log('out');
          vue.$store.dispatch('showTx', {
            text: res.message
          });
          if (vue.$refs && vue.$refs.orderScroller) {
            vue.$refs.orderScroller.finishInfinite(true);
          }
        }
      },
      function (err) {
        // 响应错误回调
        vue.$store.commit('closePop');
        if (errCb) {
          errCb(err)
        } else {
          vue.$store.dispatch('showTx', {
            text: err.message || '网络错误，请重试'
          });
          vue.$router.go(-1);
        }
      }
    );
  },
  $ajax: function (data, action, vue, callbak) {
    vue.$store.commit('showLoading');
    $.ajax({
      url: vue.$RS[action],
      type: 'POST',
      data: data,
      dataType: 'json',
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      success: function (data) {
        vue.$store.commit('closePop');
        console.log(data);
        if (data.code === 1000) {
          if (callbak) {
            callbak(data);
          }
        } else if (data.code === 4110 || data.code === 2066) {
          vue.$store.dispatch('showTx', {
            text: '你需要重新登录'
          });
          vue.$router.push('/login');
        }
      },
      error: function (data) {
        vue.$store.commit('closePop');
        console.log(data);
      }
    })
  }
}
